/*
 * Project: book
 * 
 * File Created at 2017年9月12日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.common.sensitive;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Type SensitiveWordFilter.java
 * @Desc 敏感词过滤
 * @author wanghb
 * @date 2017年9月12日 下午12:33:32
 * @version 
 */
public class SensitiveWordFilter {


    @SuppressWarnings("rawtypes")
    private Map sensitiveWordMap = null;
    public static int minMatchType = 1; //最小匹配规则
    public static int maxMatchType = 2; //最大匹配规则

    /**
     * 构造函数，初始化敏感词库
     * @throws Exception 
     * @since 1.8
     * @author whb
     */
    public SensitiveWordFilter() throws Exception {
        sensitiveWordMap = new SensitiveWordInit().initKeyWord();
    }

    /**
     * 检查文字中敏感词的长度
     * @param txt
     * @param beginIndex
     * @param matchType
     * @return 如果存在，则返回敏感词字符的长度，不存在返回0
     * @since 1.8
     * @author whb
     */
    @SuppressWarnings("rawtypes")
    public int checkSensitiveWord(String txt, int beginIndex, int matchType) {
        Map nowMap = sensitiveWordMap;
        boolean flag = false; //敏感词结束标识位：用于敏感词只有1位的情况
        char word = 0;
        int matchFlag = 0; //匹配标识数默认为0
        for (int i = beginIndex; i < txt.length(); i++) {
            word = txt.charAt(i);
            nowMap = (Map) nowMap.get(word); //获取指定key
            if (nowMap == null) {
                break;//不存在，直接返回
            }
            //输入的字(排列组合的匹配)出现在敏感词库中，判断是否为最后一个
            matchFlag++; //找到相应key，匹配标识+1
            if (isEnd(nowMap)) { //如果为最后一个匹配规则,结束循环，返回匹配标识数
                flag = true; //结束标志位为true 
                if (SensitiveWordFilter.minMatchType == matchType) {
                    break;//最小规则，直接返回,最大规则还需继续查找
                }
            }
        }
        if (matchFlag < 2 || !flag) { //长度必须大于等于1，为词 
            matchFlag = 0;
        }
        return matchFlag;
    }

    /**
     * 是否包含敏感词
     * @param txt
     * @param matchType
     * @return true：是；false：否
     * @since 1.8
     * @author whb
     */
    public boolean isContaintSensitiveWord(String txt, int matchType) {
        boolean flag = false;
        for (int i = 0; i < txt.length(); i++) {
            int matchFlag = this.checkSensitiveWord(txt, i, matchType);
            if (matchFlag > 0) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 是否包含敏感词(重庆项目默认值，按最小匹配规则来，只要有敏感词就ok)
     * 如果敏感词库为：
     *          中
     *          中国
     *          中国人
     *  初始化之后为：{中={isEnd=1, 国={人={isEnd=1}, isEnd=1}}}
     *  测试的文字为：我是一名中国人。
     *  1、按最小规则匹配，  匹配 中 的时候，就为最后一个了 直接break。
     *  2、按最大规则匹配，  匹配 中 的时候，就为最后一个，继续匹配 国，人。
     * @param txt
     * @return true：是；false：否
     * @since 1.8
     * @author whb
     */
    public boolean isSensitive(String txt) {
        boolean flag = false;
        for (int i = 0; i < txt.length(); i++) {
            int matchFlag = this.checkSensitiveWord(txt, i, 1);
            if (matchFlag > 0) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 获取文字中的敏感词
     * @param txt
     * @param matchType
     * @return
     * @since 1.8
     * @author whb
     */
    public Set<String> getSensitiveWord(String txt, int matchType) {
        Set<String> sensitiveWordList = new HashSet<String>();
        for (int i = 0; i < txt.length(); i++) {
            int length = checkSensitiveWord(txt, i, matchType);
            if (length > 0) { //存在,加入list中
                sensitiveWordList.add(txt.substring(i, i + length));
                i = i + length - 1; //减1的原因，是因为for会自增
            }
        }
        return sensitiveWordList;
    }

    /**
     * 替换敏感字字符
     * @param txt
     * @param matchType
     * @param replaceChar
     * @return
     * @since 1.8
     * @author whb
     */
    public String replaceSensitiveWord(String txt, int matchType, String replaceChar) {
        String resultTxt = txt;
        Set<String> set = this.getSensitiveWord(txt, matchType); //获取所有的敏感词
        Iterator<String> iterator = set.iterator();
        String word = null;
        String replaceString = null;
        while (iterator.hasNext()) {
            word = iterator.next();
            replaceString = getReplaceChars(replaceChar, word.length());
            resultTxt = resultTxt.replaceAll(word, replaceString);
        }
        return resultTxt;
    }

    /**
     * 获取替换字符串
     * @param replaceChar
     * @param length
     * @return
     * @since 1.8
     * @author whb
     */
    private String getReplaceChars(String replaceChar, int length) {
        String resultReplace = replaceChar;
        for (int i = 1; i < length; i++) {
            resultReplace += replaceChar;
        }
        return resultReplace;
    }

    /**
     * 判断是否为最后一个
     * @param nowMap
     * @return
     * @since 1.8
     * @author whb
     */
    @SuppressWarnings("rawtypes")
    private boolean isEnd(Map nowMap) {
        boolean flag = false;
        if ("1".equals(nowMap.get("isEnd"))) {
            flag = true;
        }
        return flag;
    }

    public static void main(String[] args) throws Exception {
        SensitiveWordFilter filter = new SensitiveWordFilter();
        System.out.println("敏感词的数量：" + filter.sensitiveWordMap.size());
        String string = "王弘博是个大坏蛋，他竟然吸食白粉和冰毒";
        System.out.println("待检测语句的字数：" + string.length());
        long beginTime = System.currentTimeMillis();
        Set<String> set = filter.getSensitiveWord(string, 1);
         String result = filter.replaceSensitiveWord(string, 1, "*");
        boolean flag = filter.isSensitive(string);
        System.out.println(flag);
        long endTime = System.currentTimeMillis();
          System.out.println("语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
         System.out.println("敏感词处理之后为："+result);
        System.out.println("总共消耗时间为：" + (endTime - beginTime));
    }

}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月12日 wanghb create
 */